package com.itheima;

import com.itheima.utlis.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;

import java.io.IOException;


//@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override//启动服务器时运行
    public void init ( FilterConfig filterConfig ) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override//访问规定的路径时运行
    public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        String url = req.getRequestURL().toString();
        if (url.contains("/login")) {
            chain.doFilter(request, response);
            return;
        }
        String token = req.getHeader("token");
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            rep.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override//关闭服务器时运行
    public void destroy () {
        Filter.super.destroy();
    }
}
